<?php


use App\Library\Utils\Arr;
use Phinx\Seed\AbstractSeed;
use Faker\Factory as FakerFactory;

class CourseUserSeeder extends AbstractSeed
{
    public function getDependencies(): array
    {
        return [
            'CourseSeeder',
            'UserSeeder',
        ];
    }

    /**
     * Run Method.
     *
     * Write your database seeder using this method.
     *
     * More information on writing seeders is available here:
     * https://book.cakephp.org/phinx/0/en/seeding.html
     */
    public function run()
    {
        $faker = FakerFactory::create('zh_CN');

        $courses = $this->fetchAll('SELECT * FROM kg_course');
        $users = $this->fetchAll('SELECT * FROM kg_user');

        $rows = [];
        for ($i = 0; $i < 1000; $i++) {
            $create = time() - rand(0, 86400 * 5);
            $expiry = $create + 86400 * 3;
            $rows[] = [
                'course_id' => Arr::rand($courses)['id'],
                'user_id' => Arr::rand($users)['id'],
                'plan_id' => $faker->date('Ymd'),
                'role_type' => rand(1, 2),
                'source_type' => rand(1, 3),
                'duration' => rand(0, 8000),
                'progress' => rand(0, 100),
                'reviewed' => 0,
                'expiry_time' => $expiry,
                'create_time' => $create,
                'update_time' => $create,
            ];
        }
        $this->table('kg_course_user')->insert($rows)->saveData();

        // update user
        $userCourses = $this->fetchAll('SELECT user_id, count(*) AS count FROM kg_course_user GROUP BY user_id');
        foreach ($userCourses as $uc) {
            $id = $uc['user_id'];
            $count = $uc['count'];
            $this->execute("UPDATE kg_user SET course_count={$count} WHERE id={$id}");
        }
    }

}
